package understanding.a7;

import sun.misc.ClassLoaderUtil;

import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义类加载器 加载
 * 和系统应用程序加载的类不同
 * @author yuan
 */
public class EG7_8 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        ClassLoader myloader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    String fileName = name.substring(name.lastIndexOf('.') + 1) + ".class";
                    InputStream is = getClass().getResourceAsStream(fileName);
                    if (is == null) {
                        return super.loadClass(name);
                    }
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    return defineClass(name, b, 0, b.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException(name);
                }
            }
        };
        Object obj = myloader.loadClass("understanding.a7.ClassLoaderTest").newInstance();
        System.out.println(obj.getClass());
        System.out.println(obj instanceof understanding.a7.ClassLoaderTest);

    }
}
/* output
class understanding.a7.ClassLoaderTest
false
 */